package cn.zhaozhiqi.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.zhaozhiqi.domain.Login;
import cn.zhaozhiqi.exc.BussinessException;
import cn.zhaozhiqi.mapper.LoginMapper;
import cn.zhaozhiqi.service.ILoginService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class LoginServiceImpl implements ILoginService {

    ConcurrentHashMap<String,Login> map= new ConcurrentHashMap<String,Login>();

    public ConcurrentHashMap<String, Login> getMap() {
        return map;
    }

    @Autowired
    private LoginMapper loginMapper;
    @Override
    public String loginByAccount(Login login) {
        String username = login.getUsername();
        String password = login.getPassword();
        //1.判断用户名和密码不能为空；
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            throw new BussinessException("用户名和密码不能为空");
        }
        //2.根据用户名查询是否存在这个对象，不存在抛出异常，存在继续校验密码是否一致
        Login exp = loginMapper.loginByName(username);
        if (ObjectUtil.isEmpty(exp)){
            throw new BussinessException("用户不存在");
        }
        //3.用户若存在，判断密码是否相同
        if (!password.equals(exp.getPassword())){
            throw new BussinessException("密码错误！");
        }

        //4.校验成功，存储账号密码，返回token
        UUID uuid = UUID.randomUUID();
        map.put(uuid.toString(),login);
        return uuid.toString();
    }
}
